import { StructureAnimationMode } from "@minecraft/server";
import { GameComponent, regionHelper } from "@sapi-game/main";
import { ScriptRunner } from "@sapi-game/Runner/scriptRunner";
import { PillarOfFortuneLoadingState } from "../states/loadingState";
import { PillarOfFortuneWatingRoom } from "./waitingRoom";
import { Logger } from "@sapi-game/utils";
import { EntityTypeIds } from "@sapi-game/utils/vanila-data";

/**加载地图 */
export class POFMapLoader extends GameComponent<PillarOfFortuneLoadingState> {
    private readonly logger = new Logger(this.constructor.name);

    override onAttach(): void {
        this.runner.run(this.process.bind(this));
    }

    async process(r: ScriptRunner) {
        try {
            await r.wait(20);
            this.context.players.title("地图正在重置中...");
            await this.fillAir();
            await r.wait(1);
            this.killEntity();
            await this.fillAir();
            await r.wait(10);
            this.context.map.structure.place({
                animationMode: StructureAnimationMode.Layers,
                animationSeconds: 4,
            });
            await r.wait(90);
            this.state
                .getComponent(PillarOfFortuneWatingRoom)
                .placeWatingRoom();
            await r.wait(10);
            this.state.next();
        } catch (err) {
            this.logger.error("错误", err);
            this.context.players.sendMessage("§c地图重置失败，正在结束游戏");
            this.state.end();
        }
    }

    fillAir(): Promise<void> {
        const generator = regionHelper.fillGenerator(
            this.context.map.region,
            "minecraft:air"
        );
        const { promise } = this.runner.runJob(generator);
        return promise;
    }

    killEntity() {
        const entites = this.context.outSetRegion.getEntitesInRegion({
            excludeTypes: [EntityTypeIds.Player],
        });
        entites.forEach((e) => e.remove());
    }
}
